package com.qf.controlle;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.qf.common.MyThreadLocal;
import com.qf.common.R;
import com.qf.entity.Employee;
import com.qf.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private HttpServletRequest request;

    /**
     * 登录功能
     *
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody Employee employee) {
        //1.接收参数,检查参数
        if (employee == null) {
            return R.error("参数异常,请重新输入!");
        }
        //2.通过前端传入的密码进行加密:加密密码
        String password = employee.getPassword();
        String pass = DigestUtils.md5DigestAsHex(password.getBytes());
        //3.通过传进来的userid查询用户是否存在
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Employee::getUsername, employee.getUsername());
        Employee one = employeeService.getOne(wrapper);
        //3.判断用户是否存在
        if (one == null) {
            return R.error("该用户不存在!");
        }
        //4.判断密码是否正确
        if (!one.getPassword().equals(pass)) {
            return R.error("您的密码不正确,请重新输入!");
        }
        //5.判断用户是否处于禁用状态
        if (one.getStatus() == 0) {
            return R.error("该用户已禁用!");
        }
        //6.获取session,把用户id存入session当中
        HttpSession session = request.getSession();
        session.setAttribute("userId", one.getId());
        return R.success(one);
    }

    /**
     * 退出功能
     *
     * @return
     */
    @PostMapping("/logout")
    public R logOut() {
        //得到session
        HttpSession session = request.getSession();
        //清空session信息
        session.setAttribute("employee", null);
        return R.success("退出成功!");
    }

    /**
     * 添加用户
     *
     * @param employee
     * @return
     */
    @PostMapping
    public R add(@RequestBody Employee employee) {
        //查询是否存在该用户
        LambdaQueryWrapper<Employee> wapper = new LambdaQueryWrapper<>();
        wapper.eq(Employee::getUsername, employee.getUsername());
        Employee one = employeeService.getOne(wapper);
        //判断是否存在该用户
        if (one != null) {
            return R.error("添加失败!该用户已存在!");
        }
        //不存在该用户,补全数据库字段
        // employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());
        //通过session得到登录的用户的userid,为long类型
        //HttpSession session = request.getSession();
        //Long userId = (Long) session.getAttribute("userId");
        //设置传入id
        // employee.setCreateUser(userId);
        //employee.setUpdateUser(userId);
        //设置初始值密码,首先加密码
        String pw = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(pw);
        //调用service添加
        boolean save = employeeService.save(employee);
        if (save == false) {
            return R.error("添加失败!请重试!");
        }
        return R.success("添加成功!");
    }

    /**
     * 分页查询,
     * 名字模糊查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, String name) {
        //添加分页拦截器对象
        IPage<Employee> pageInfo = new Page<>(page, pageSize);
        //条件查询器
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        //如果有名字的时候
        if (name != null) {
            wrapper.like(Employee::getName, name);
        }
        //获得两个条件查询
        IPage<Employee> pageName = employeeService.page(pageInfo, wrapper);
        return R.success(pageName);
    }

    /**
     * 修改状态
     *
     * @param employee
     * @return
     */
    @PutMapping
    public R update(@RequestBody Employee employee) {

        //MyThreadLocal替换http
        Long userId = MyThreadLocal.getCreateUser();

        //如果是管理员不能被别人编辑
        if (userId != 1l && employee.getId().longValue() == 1l) {
            return R.error("管理员不能被操作!");
        }
        //根据id获取对象
        Employee emp = employeeService.getById(employee.getId());
        //如果该用户不存在
        if (emp == null) {
            return R.error("该用户不存在!");
        }
        //更新状态
        //employee.setStatus(employee.getStatus());
        //更新修改时间
        //employee.setUpdateTime(LocalDateTime.now());
        //更新修改用户的userid
        //通过session得到登录的用户的userid,为long类型
       /* HttpSession session = request.getSession();
        Long userId = (Long) session.getAttribute("userId");*/


        // employee.setCreateUser(userId);
        // employee.setUpdateUser(userId);
        //所有用户都可以被管理员或者自己修改状态和信息
        if (userId.longValue() == employee.getId().longValue() || userId.longValue() == 1l) {
            //更新数据库
            employeeService.updateById(employee);
            return R.success("修改状态成功!");
        }
        return R.error("权限不足!");
    }

    /**
     * 根据id查询对象,回显数据
     *
     * @param id
     * @return
     */
    @GetMapping("/{userId}")
    public R<Employee> findById(@PathVariable("userId") Long id) {
        //根据id查询对象
        Employee byId = employeeService.getById(id);
        //判断该对象是否存在
        if (byId == null) {
            //不存在返回一个信息
            return R.error("没有查到该用户的信息!");
        }
        //当对象存在回显数据
        return R.success(byId);
    }
}
